/**
 * 编辑器键盘快捷键 Composable
 * 
 * 提供键盘快捷键功能
 */
import { onMounted, onBeforeUnmount } from 'vue';

export function useEditorShortcuts(handlers) {
  const {
    onSave = () => {},
    onPublish = () => {},
    onBack = () => {}
  } = handlers || {};

  /**
   * 处理键盘事件
   * 
   * @param {KeyboardEvent} event 键盘事件
   */
  const handleKeyDown = (event) => {
    // Ctrl/Cmd + S: 保存草稿
    if ((event.ctrlKey || event.metaKey) && event.key === 's') {
      event.preventDefault();
      onSave();
      return;
    }

    // Ctrl/Cmd + Enter: 发布文章
    if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
      event.preventDefault();
      onPublish();
      return;
    }

    // Esc: 返回
    if (event.key === 'Escape') {
      event.preventDefault();
      onBack();
      return;
    }
  };

  onMounted(() => {
    window.addEventListener('keydown', handleKeyDown);
  });

  onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleKeyDown);
  });

  return {
    handleKeyDown
  };
}

